package com.hengpeng.itfinoss.controller.article;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.persist.Article;
import com.hengpeng.itfinbase.persist.ArticleCategory;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * 新闻类别控制器
 * </pre>
 * @author pengfangliang
 * @version 1.0, 2010-8-11
 */
@Controller
@RequestMapping("/cm")
public class ArticleCategoryController extends BaseController
{
	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public ModelAndView preCreate()
	{
		ModelAndView modelAndView = new ModelAndView("/article/category/detail");
		Set<ArticleCategory> categorys = serviceFactory.getArticleCategorySerivce().findAllArticleCategorySort(null)
				.getReturnValue();
		modelAndView.addObject("category", new ArticleCategory());
		modelAndView.addObject("categorys", categorys);
		return modelAndView;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String add(HttpServletRequest request, ModelMap map)
	{
		ArticleCategory model = new ArticleCategory();
		model.setName(request.getParameter("name"));
		model.setDescription(request.getParameter("description"));
		model.setVersion(Long.parseLong(request.getParameter("version")));
		try
		{
			ServiceResult<ArticleCategory> result = serviceFactory.getArticleCategorySerivce().save(model);
			return returnSuccess(map, result, "/cm/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.POST)
	public String update(@PathVariable long id, HttpServletRequest request, ModelMap map)
	{
		String pId = request.getParameter("parent");
		ArticleCategory model = serviceFactory.getArticleCategorySerivce().get(id).getReturnValue();
		model.setName(request.getParameter("name"));
		model.setDescription(request.getParameter("description"));
		model.setVersion(Long.parseLong(request.getParameter("version")));
		try
		{
			if ((!StringHelper.isEmpty(pId)) && (!"0".equals(pId)))
			{
				ArticleCategory parent = serviceFactory.getArticleCategorySerivce().get(Long.parseLong(pId))
						.getReturnValue();
				model.setParent(parent);
			}
			else
			{
				model.setParent(null);
			}
			ServiceResult<ArticleCategory> result = serviceFactory.getArticleCategorySerivce().update(model);
			return returnSuccess(map, result, "/cm/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/remove")
	public String delete(ModelMap map, HttpServletRequest request, Long[] ids)
	{
		if (ids == null || ids.length <= 0)
		{
			return returnError(map, "要删除的类别不能为空");
		}
		List<ArticleCategory> children = serviceFactory.getArticleCategorySerivce().findChildByIds(ids)
				.getReturnValue();
		if (children.size() > 0)
		{
			return returnError(map, "您删除的列别存在子类别，请选择最小级别的子类别删除！");
		}
		List<Article> artilces = serviceFactory.getArticleService().findArticleByCategoryIds(ids).getReturnValue();
		if (artilces.size() > 0)
		{
			return returnError(map, "您删除的类别中存在关联新闻，不能删除！");
		}
		try
		{
			Set<Object> set = new HashSet<Object>(Arrays.asList(ids));
			ServiceResult<ArticleCategory> result = serviceFactory.getArticleCategorySerivce().delete(set);
			return returnSuccess(request, map, result, "/cm/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, ModelMap map, String name, Long parent)
	{
		/** 保存表单 */
		map.put("name", name);
		map.put("parent", parent);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			LinkedHashMap<String, OrderType> sortMap = new LinkedHashMap<String, OrderType>();
			sortMap.put("id", OrderType.DESC);
			List<ArticleCategory> list = serviceFactory.getArticleCategorySerivce()
					.findArticleCategoryPage(name, parent, page.currentPage, page.pageSize, sortMap).getReturnValue();
			Long count = serviceFactory.getArticleCategorySerivce().findArticleCategoryCount(name, parent)
					.getReturnValue();
			// 查询所有顶级分类
			List<ArticleCategory> parents = serviceFactory.getArticleCategorySerivce().findLevelArticleCategory(null);
			page.setEntityCount(count.intValue());
			map.put("parents", parents);
			map.put("articlecategorylist", list);
			map.put("articleCategoryListPage", page);
			return "/article/category/categorymanage";
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/get/{id}")
	public ModelAndView get(@PathVariable Long id, ModelMap map)
	{
		if (id == null)
		{
			return new ModelAndView(returnError(map, "类别ID不能为空"));
		}
		try
		{
			ArticleCategory articleCategory = serviceFactory.getPersistService().get(ArticleCategory.class, id);
			ModelAndView modelAndView = new ModelAndView("/article/category/detail");
			modelAndView.addObject("category", articleCategory);
			modelAndView.addObject("categorys",
					serviceFactory.getArticleCategorySerivce().findAllArticleCategorySort(id).getReturnValue());
			return modelAndView;
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return new ModelAndView(returnError(map, ex));
		}
	}
}
